package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * 只有是实例方法才能够拦截, 对静态资源以及正常请求不进行拦截
         * 这样浏览器发送请求为OPTION时,就可以收到服务器反馈,最后浏览器能够发送真实请求GET
         */
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        // 拿到handler对象, 判断是否贴有RequireLogin注解
        HandlerMethod hm = (HandlerMethod) handler;
        if(hm.hasMethodAnnotation(RequireLogin.class)) {
            if (user == null){
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }

}
